package org.flower.web.servlet;

import com.jspsmart.upload.*;
import org.flower.bean.CommodityClass;
import org.flower.dao.CommodityDetailsDao;
import org.flower.dao.impl.CommodityDetailsDaoImpl;
import org.flower.entity.CommodityDetails;
import org.flower.service.CommodityClassService;
import org.flower.service.impl.CommodityClassServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author Aizen
 */
@WebServlet("/manager/updateCommodityServlet.shtml")
public class UpdateCommodityServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取到参数（某个商品的ID）
        String cid = request.getParameter("cid");
        String pageNo = request.getParameter("pageNo");
        request.setAttribute("pageNo",pageNo);
        CommodityDetailsDao detailsDao = new CommodityDetailsDaoImpl();
        //根据商品ID拿到该商品
        CommodityDetails comdetails = detailsDao.getComdetailsById(Integer.parseInt(cid));

        //分割商品图片
        String comImage = comdetails.getComImage();
        String[] split = comImage.split(",");
        for (String str:split) {
            comdetails.getImages().add(str);
        }

        //分割商品详情图片
        String detailsImage = comdetails.getDetailsImage();
        String[] split1 = detailsImage.split(",");
        for (String str1:split1) {
            comdetails.getImages2().add(str1);
        }


        //拿所有类别信息
        CommodityClassService classServlet = new CommodityClassServiceImpl();
        List<CommodityClass> classList = classServlet.findAll();
        request.setAttribute("classList",classList);


        //拿所有商品的id
        CommodityDetailsDao cd = new CommodityDetailsDaoImpl();
        List<CommodityDetails> commodityDetailsList = cd.getCommodityDetails();
        request.setAttribute("commodityDetailsList",commodityDetailsList);


        //放到request作用域中
        request.setAttribute("comdetails",comdetails);
        //转发到页面进行信息展示
        request.getRequestDispatcher("updateCommodity.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //商品对象
        CommodityDetails details = new CommodityDetails();

        //1.实例化对象
        SmartUpload smartUpload = new SmartUpload();
        //2.设置编码
        smartUpload.setCharset("utf-8");
        //3.初始化
        smartUpload.initialize(this,request,response);
        try {
            //4.文件上传
            smartUpload.upload();
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
        //5.获取request对象
        Request req = smartUpload.getRequest();

        //封装对象
        String id = req.getParameter("id");
        details.setId(Integer.parseInt(id));
        String comName = req.getParameter("comName");
        details.setComName(comName);
        String content1 = req.getParameter("content");
        details.setContent(content1);
        String content21 = req.getParameter("content2");
        details.setContent2(content21);
        String outNum = req.getParameter("outNum");
        details.setOutNum(Integer.parseInt(outNum));
        String outPrice = req.getParameter("outPrice");
        details.setOutPrice(Double.parseDouble(outPrice));
        String marketPrice = req.getParameter("marketPrice");
        details.setMarketPrice(Double.parseDouble(marketPrice));
        String materialScience = req.getParameter("materialScience");
        details.setMaterialScience(materialScience);
        String packing = req.getParameter("packing");
        details.setPacking(packing);
        String distribution = req.getParameter("distribution");
        details.setDistribution(distribution);
        String comShowId = req.getParameter("comShowId");
        if(comShowId.equals("0")){
            CommodityDetailsDao cd = new CommodityDetailsDaoImpl();
            Integer maxNo = cd.getMaxNo();
            comShowId =  maxNo+1+"";
        }
        details.setComShowId(Integer.parseInt(comShowId));
        String classId = req.getParameter("classId");
        details.setClassId(Integer.parseInt(classId));
        String stockd = req.getParameter("stockd");
        details.setStockd(Integer.parseInt(stockd));


        Files files = smartUpload.getFiles();

        String comimage = "";
        String detailsimage = "";

        boolean comi = false;
        boolean dei = false;
        for (int i = 0; i < files.getCount(); i++) {
            File file = files.getFile(i);

            //如果上传了文件
            if(!file.isMissing()){
                if(file.getFieldName().equals("comImage")){
                    comi = true;
                    try {
                        file.saveAs("/image/commodity/"+file.getFileName());
                        comimage += file.getFileName()+",";
                    } catch (SmartUploadException e) {
                        e.printStackTrace();
                    }
                }else if(file.getFieldName().equals("detailsImage")){
                    dei = true;
                    try {
                        file.saveAs("/image/commodity/"+file.getFileName());
                        detailsimage += file.getFileName()+",";
                    } catch (SmartUploadException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        //全部没上传
        if(!comi&&!dei){
            String[] comImages = req.getParameterValues("comImages");
            for (String img:comImages) {
                comimage += img+",";
            }
            String[] detailsImages = req.getParameterValues("detailsImages");
            for (String img:detailsImages) {
                detailsimage += img+",";
            }
        }else if(comi&&!dei){
            //1上传
            String[] detailsImages = req.getParameterValues("detailsImages");
            for (String img:detailsImages) {
                detailsimage += img+",";
            }
        }else if(!comi&&dei){
            //2上传
            String[] comImages = req.getParameterValues("comImages");
            for (String img:comImages) {
                comimage += img+",";
            }
        }

        details.setComImage(comimage);
        details.setDetailsImage(detailsimage);


        //处理商品描述信息
        String content2 = req.getParameter("content2");
        String content = req.getParameter("content");
        content+="split";
        content+=content2;
        details.setContent(content);

        //获取系统当前时间设置商品添加时间
//        Date date = new Date();
//        details.setInsertDate(date);

        //调用底层进行商品信息的修改
        CommodityDetailsDao detailsDao = new CommodityDetailsDaoImpl();
        //接收修改结果
        boolean b = detailsDao.updateCommodity(details);
        //如果修改成功了就跳到商品信息列表，否则还是回到该页面
        if(b){
            request.getRequestDispatcher("commodityListServlet").forward(request,response);
        }else{
            response.sendRedirect("updateCommodity.jsp");
        }

    }
}
